import { CURRENT_DOMAIN } from "../data/request/route";

/**
 * @class 防抖封装
 */
export class Debounce {
  public use = (delay: number): Function => {
    let timer: number | undefined = undefined;
    return (): Promise<void> => {
      return new Promise((resolve, reject) => {
        if (timer) {
          clearTimeout(timer);
        }
        timer = setTimeout(() => {
          resolve();
          timer = undefined;
        }, delay)
      })
    }
  }
}
/**
 * @function 节流封装
 */
export function Throttle() {
  let timer: number | undefined = undefined;
  return (delay: number): Promise<void> => {
    return new Promise((resolve, reject) => {
      if (timer) {
        timer = setTimeout(() => { }, delay);
        reject();
      }
      else {
        resolve();
        timer = setTimeout(() => {
          if (timer) {
            clearTimeout(timer);
            timer = undefined;
          }
        }, delay)
      }
    })
  }
}

/**
 * @function 身份证合法性检查
 * @version 2.0 精确日期检验、校验码合法性检验
 */
export function CheckIdNum(origin: string): boolean {
  const regExp: RegExp = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/; // 正则
  var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
  var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
  var code = origin.substring(17);
  if (regExp.test(origin)) {
    var sum = 0;
    for (var i = 0; i < 17; i++) {
      sum += parseInt(origin[i]) * factor[i];
    }
    if (parity[sum % 11] == code.toUpperCase()) {
      return true;
    }
  }
  return false;
}

/**
 * @function 验证手机号合法性
 * @param origin: string 传入手机号 
 */
export function CheckPhone(origin: string): boolean {
  const regExp: RegExp = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
  if (regExp.test(origin)) { return true; }
  return false;
}

/**
 * @function 获取到DOM文档后进行处理进行纯文本的节选显示
 */
export function DOMTextFormat(DOM: string): string {
  let result = DOM.replace(/<\/?.+?>/g, ''); // 删除所有DOM标签
  result = result.replace(/\s+/g, ''); // 删除所有空格
  if (result.length > 50) {
    // 字数过多进行剪切处理
    result = `${result.slice(0, 50)}...`;
  }
  return result;
}
/**
 * @class 日期类
 */
export class LocalDate {
  private Year: number;
  private Month: number;
  private Date: number;
  private DayList: Array<number> = [];  // 月份对应天数
  private getDayList = () => {
    this.DayList = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    // 判断平闰年
    if (this.Year % 400 == 0 || (this.Year % 4 == 0 && this.Year % 100 != 0)) {
      // 闰年
      this.DayList[1] = 29;
    }
  }
  /**
   * @constructor 构造日期类
   * @param date 形如xxxx-xx-xx的字符串
   */
  constructor(date: string) {
    const dateArray = date.split('-'); // 解析字符串
    this.Year = parseInt(dateArray[0]);
    this.Month = parseInt(dateArray[1]);
    this.Date = parseInt(dateArray[2]);
    this.getDayList();
  }
  /**
   * @function 设置日期
   */
  public setDate(date: string) {
    const dateArray = date.split('-'); // 解析字符串
    this.Year = parseInt(dateArray[0]);
    this.Month = parseInt(dateArray[1]);
    this.Date = parseInt(dateArray[2]);
  }
  /**
   * @function 获取年份
   */
  public getYear(): number {
    return this.Year;
  }
  /**
   * @function 获取月份
   */
  public getMonth(): number {
    return this.Month;
  }
  /**
   * @function 获取日期
   */
  public getDate(): number {
    return this.Date;
  }
  /**
   * @function 获取日期字符串
   */
  public getDateStr(): string {
    const month: any = this.Month < 10 ? '0' + this.Month : this.Month; // 转换为日期标准范式
    const date: any = this.Date < 10 ? '0' + this.Date : this.Date;
    return `${this.Year}-${month}-${date}`;
  }
  /**
   * @function 增加天数
   */
  public addDay(day: number | string): string {
    if (typeof day == "string") {
      day = parseInt(day);
    }
    let year: any = this.Year;
    let month: any = this.Month;
    let date: any = this.Date + day;
    while (date > this.DayList[month - 1]) {
      date -= this.DayList[month - 1];
      month++;
      if (month > 12) {
        month = 1;
        year++;
      }
    }
    month = month < 10 ? '0' + month : month; // 转换为字符串
    date = date < 10 ? '0' + date : date;
    return `${year}-${month}-${date}`;
  }
}
function formatNumber(n: number): string {
  let str: string = n.toString()
  return str.length == 2 ? str : ('0' + str);
}
/**
 * 时间戳转化为年 月 日 时 分 秒
 * number: 传入时间戳
 * format：返回格式，支持自定义，但参数必须与formateArr里保持一致
 */
function FormatTime(number: number, format: string) {

  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  var returnArr: Array<string> = [];

  var date = new Date(number * 1000);
  returnArr.push((date.getFullYear()).toString());
  returnArr.push(formatNumber(date.getMonth() + 1));
  returnArr.push(formatNumber(date.getDate()));

  returnArr.push(formatNumber(date.getHours()));
  returnArr.push(formatNumber(date.getMinutes()));
  returnArr.push(formatNumber(date.getSeconds()));

  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
}
interface File {
  tempFilePath: string, // 临时文件路径 
  id: string, // 用户ID
  id_flag: string, // 用户身份 'teacher' | 'student' | 'parent',
  fileType: string, // 文件类型
  [key: string]: string
}
/**
   * @function 图片上传服务器
   */
export async function UploadFile(options: File): Promise<WechatMiniprogram.UploadFileSuccessCallbackResult> {
  return new Promise((resolve, reject) => {
    console.log(FormatTime((new Date()).getTime() / 1000, 'YMDhms'))
    wx.uploadFile({
      url: CURRENT_DOMAIN + 'WxUser/SaveImg',
      filePath: options.tempFilePath,
      name: 'file',
      formData: {
        // 图片命名
        newName: FormatTime((new Date()).getTime() / 1000, 'YMDhms'),
        id: options.id,
        modelName: options.id_flag == 'student' ? 'Userinfo' : options.id_flag == 'parent' ? 'UserParent' : 'Teacher',
        file_type: options.fileType,
      },
      success: res => {
        console.log(res);
        resolve(res);
      },
      fail: err => {
        reject(err);
      }
    })
  })
}
/**
 * @interface 更多文件
 */
interface _MoreFile {
  tempFilePath: string, // 临时文件路径 
  fileName: string, // 文件命名
  userid: string, // 用户id
  [key: string]: string
}
/**
 * @function 上传更多图像文件（粤康码）
 */
export async function UploadMoreImg(data: _MoreFile) {
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url: CURRENT_DOMAIN + 'WxUser/SaveMoreImg',
      filePath: data.tempFilePath,
      name: 'file',
      formData: {
        newName: data.fileName, // 图像命名
        file_type: '',
        id: data.userid, // 用户id
      },
      success: res => {
        resolve(res);
      },
      fail: err => {
        reject(err);
      }
    })
  })
}
